import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Tabs, Button, message, Divider, Dropdown, Menu } from 'antd';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import Authorized from '@/utils/Authorized';

const { TabPane } = Tabs;

@connect(({ localpolicy, loading }) => ({
  localpolicy,
  loading: loading.models.localpolicy,
}))
@Form.create()
class Combina extends PureComponent {
  state = {
    selectedRowKeys: [], // 社保组合的选中id组合
    selectedRows: [],
    accuSelectedRowKeys: [], // 公积金组合的选中id组合
    accuSelectedRows: [],
    tabkey: 1, // 是哪个组合（ 社保或者公积金 ）
  };

  componentDidMount() {}

  // 改变页签
  changeTabs = index => {
    const { dispatch, localpolicy } = this.props;
    this.setState({ tabkey: index }, () => {
      this.getPkgList(localpolicy.areaId, 1, 10);
    });
    dispatch({
      type: 'localpolicy/combinationmessage',
      payload: index,
    });
  };

  // 改变页签
  getPkgList = (areaId, currentPage, pageSize) => {
    const { tabkey } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: Number(tabkey) === 1 ? 'localpolicy/getInsList' : 'localpolicy/getAccuList',
      payload: {
        areaId,
        pagerArg: {
          currentPage,
          pageSize,
        },
      },
    });
  };

  // 跳转社保添加组合
  goSocialAdd = joinIdeList => {
    const { localpolicy } = this.props;
    const { areaId } = localpolicy;
    const combinationList = [];
    joinIdeList.forEach(item => {
      if (item.ideId) {
        combinationList.push(item);
      }
    });
    router.push(
      `/more/policyprotect/add?state=1&areaId=${areaId}&information=${combinationList.length}`
    );
  };

  // 公积金添加组合
  goFoundAdd = () => {
    const { localpolicy } = this.props;
    const { areaId } = localpolicy;
    router.push(`/more/policyprotect/foundAdd?areaId=${areaId}`);
  };

  // 社保
  detail = () => {
    router.push('/policymanagement/localpolicymaintenance/detail');
  };

  // 社保组合 - 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { localpolicy } = this.props;
    const { areaId } = localpolicy;
    // 获取社保组合列表
    this.getInsPkgList(areaId, pagination.current, pagination.pageSize);
  };

  // 复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  // 公积金组合 - 表格有变化：比如：切换页码
  handleAccuStandardTableChange = pagination => {
    const { localpolicy } = this.props;
    const { areaId } = localpolicy;
    // 获取社保组合列表
    this.getAccuPkgList(areaId, pagination.current, pagination.pageSize);
  };

  // 复选框
  handleAccuSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ accuSelectedRowKeys: selectedRowKeys, accuSelectedRows: selectedRows });
  };

  // 社保组合设置默认值
  setTheDefault = (insLsPkgId, isState, vno) => {
    const {
      localpolicy,
      dispatch,
      insDataSource: { pagination },
    } = this.props;
    const { areaId } = localpolicy;
    dispatch({
      type: 'localpolicy/setDefault',
      payload: { insLsPkgId, vno, areaId },
    }).then(res => {
      if (res.success) {
        message.success('设置成功！');
        this.getInsPkgList(localpolicy.areaId, pagination.current, pagination.pageSize);
      } else {
        message.success(res.message || '设置失败！');
      }
    });
  };

  // 修改社保组合状态
  modifyState = (insLsPkgid, state, vno) => {
    const {
      dispatch,
      localpolicy,
      insDataSource: { pagination },
    } = this.props;
    dispatch({
      type:
        Number(state) === 1 || Number(state) === 3
          ? 'localpolicy/changeUpdateInsEnable'
          : 'localpolicy/changeUpdateInsProhibit',
      payload: { insLsPkgid, vno },
    }).then(res => {
      if (res.success) {
        message.success('状态修改成功！');
        this.getInsPkgList(localpolicy.areaId, pagination.current, pagination.pageSize);
      } else {
        message.warning(res.message || '状态修改失败！');
      }
    });
  };

  // 公积金组合 - 点击启用或者停用
  modifyFoundState = (accuLsPkgId, state, vno) => {
    const {
      localpolicy,
      dispatch,
      accuDataSource: { pagination },
    } = this.props;
    dispatch({
      type:
        Number(state) === 1 || Number(state) === 3
          ? 'localpolicy/changeUpdateEnable'
          : 'localpolicy/changeUpdateProhibit',
      payload: { accuLsPkgId, vno },
    }).then(res => {
      if (res.success) {
        message.success('状态修改成功！');
        this.getAccuPkgList(localpolicy.areaId, pagination.current, pagination.pageSize);
      } else {
        message.warning(res.message || '状态修改失败！');
      }
    });
  };

  // 删除社保组合
  delItem = record => {
    const {
      dispatch,
      localpolicy,
      insDataSource: { pagination },
    } = this.props;
    dispatch({
      type: 'localpolicy/deleteCombina',
      payload: {
        list: [
          {
            insLsPkgId: record.insLsPkgId,
            vno: record.vno,
          },
        ],
      },
    }).then(res => {
      if (res.success) {
        message.success('删除成功');
        this.getInsPkgList(localpolicy.areaId, pagination.current, pagination.pageSize);
      } else {
        message.warning(res.message || '删除失败');
      }
    });
  };

  // 删除公积金组合
  delFoundItem = record => {
    const {
      dispatch,
      localpolicy,
      accuDataSource: { pagination },
    } = this.props;
    dispatch({
      type: 'localpolicy/deleteAccuCombina',
      payload: {
        list: [
          {
            accuLsPkgId: record.accuLsPkgId,
            vno: record.vno,
          },
        ],
      },
    }).then(res => {
      if (res.success) {
        message.success('删除成功');
        this.getAccuPkgList(localpolicy.areaId, pagination.current, pagination.pageSize);
      } else {
        message.warning(res.message || '删除失败');
      }
    });
  };

  // 获取社保列表
  getInsPkgList = (areaId, currentPage, pageSize) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getInsList',
      payload: {
        areaId,
        pagerArg: {
          currentPage,
          pageSize,
        },
      },
    });
  };

  // 获取公积金组合列表
  getAccuPkgList = (areaId, nowPage, pageNum) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getAccuList',
      payload: {
        areaId,
        pagerArg: {
          currentPage: nowPage,
          pageSize: pageNum,
        },
      },
    });
  };

  // 社保组合查看详情
  insdetail = (record, areaId, tempUrl) => {
    router.push(
      `${tempUrl}/detail?` +
        `insLsPkgId=${record.insLsPkgId}&areaId=${areaId}&hshdRegFlag=${record.hshdRegFlag}`
    );
  };

  // 公积金组合查看详情
  sourdetail = (record, areaId, tempUrl) => {
    router.push(
      `${tempUrl}/foundDetail?` +
        `accuLsPkgId=${record.accuLsPkgId}&areaId=${areaId}&hshdRegFlag=${record.hshdRegFlag}`
    );
  };

  render() {
    const {
      loading,
      localpolicy,
      insDataSource,
      accuDataSource,
      tab,
      tempUrl,
      joinIdeList,
    } = this.props;
    const { selectedRowKeys, selectedRows, accuSelectedRowKeys, accuSelectedRows } = this.state;
    const { areaId } = localpolicy;
    const columns = [
      {
        title: '社保组合名称',
        dataIndex: 'insLsPkgName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: val => val || '--',
      },

      {
        title: '是否区分缴费人员类别',
        dataIndex: 'hshdRegFlagName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: val => val || '--',
      },
      {
        title: '是否该地区默认组合',
        dataIndex: 'dftFlagName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: val => val || '--',
      },
      {
        title: '状态',
        dataIndex: 'stateName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: val => val || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 150,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: (text, record) => (
          <div>
            <a onClick={() => this.insdetail(record, areaId, tempUrl)}>查看</a>
            <Authorized authority="business:insLsPkg:update" noMatch={null}>
              <Divider type="vertical" />
              <Dropdown
                overlay={
                  <Menu>
                    {record.state === 1 || record.state === 3 ? (
                      <Menu.Item>
                        <a
                          onClick={() =>
                            this.modifyState(record.insLsPkgId, record.state, record.vno)
                          }
                        >
                          启用
                        </a>
                      </Menu.Item>
                    ) : null}

                    {record.state === 2 ? (
                      <Menu.Item>
                        <a
                          onClick={() =>
                            this.modifyState(record.insLsPkgId, record.state, record.vno)
                          }
                        >
                          停用
                        </a>
                      </Menu.Item>
                    ) : null}

                    <Menu.Item>
                      <a
                        onClick={() => {
                          router.push(
                            `/more/policyprotect/edit?insLsPkgId=${
                              record.insLsPkgId
                            }&areaId=${areaId}&state=${record.state}&hshdRegFlag=${
                              record.hshdRegFlag
                            }&vno=${record.vno}`
                          );
                        }}
                      >
                        修改
                      </a>
                    </Menu.Item>

                    {record.state === 2 ? (
                      <Menu.Item>
                        <a
                          onClick={() =>
                            this.setTheDefault(record.insLsPkgId, record.state, record.vno)
                          }
                        >
                          设为默认
                        </a>
                      </Menu.Item>
                    ) : null}

                    {record.state === 1 ? (
                      <Menu.Item>
                        <a
                          onClick={() => {
                            this.delItem(record);
                          }}
                        >
                          删除
                        </a>
                      </Menu.Item>
                    ) : null}
                  </Menu>
                }
              >
                <a>
                  更多
                  <DownOutlined />
                </a>
              </Dropdown>
            </Authorized>
          </div>
        ),
      },
    ];

    const columns1 = [
      {
        title: '公积金组合名称',
        dataIndex: 'accuLsPkgName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: val => val || '--',
      },
      {
        title: '状态',
        dataIndex: 'stateName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: val => val || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 150,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: (text, record) => (
          <div>
            <a onClick={() => this.sourdetail(record, areaId, tempUrl)}>查看</a>
            <Authorized authority="business:insLsPkg:update" noMatch={null}>
              <Divider type="vertical" />
              <Dropdown
                overlay={
                  <Menu>
                    {record.state === 1 || record.state === 3 ? (
                      <Menu.Item>
                        <a
                          onClick={() =>
                            this.modifyFoundState(record.accuLsPkgId, record.state, record.vno)
                          }
                        >
                          启用
                        </a>
                      </Menu.Item>
                    ) : null}

                    {record.state === 2 ? (
                      <Menu.Item>
                        <a
                          onClick={() =>
                            this.modifyFoundState(record.accuLsPkgId, record.state, record.vno)
                          }
                        >
                          停用
                        </a>
                      </Menu.Item>
                    ) : null}

                    <Menu.Item>
                      <a
                        onClick={() => {
                          router.push(
                            `/more/policyprotect/foundEdit?accuLsPkgId=${
                              record.accuLsPkgId
                            }&areaId=${areaId}&state=${record.state}&hshdRegFlag=${
                              record.hshdRegFlag
                            }&vno=${record.vno}`
                          );
                        }}
                      >
                        修改
                      </a>
                    </Menu.Item>

                    {record.state === 1 ? (
                      <Menu.Item>
                        <a
                          onClick={() => {
                            this.delFoundItem(record);
                          }}
                        >
                          删除
                        </a>
                      </Menu.Item>
                    ) : null}
                  </Menu>
                }
              >
                <a>
                  更多
                  <DownOutlined />
                </a>
              </Dropdown>
            </Authorized>
          </div>
        ),
      },
    ];

    return (
      <div>
        <Tabs defaultActiveKey={tab} onChange={this.changeTabs}>
          <TabPane tab="社保组合" key="1">
            <Row style={{ marginBottom: 16 }}>
              <Authorized authority="business:insLsPkg:insert" noMatch={null}>
                <Button type="primary" size="default" onClick={() => this.goSocialAdd(joinIdeList)}>
                  <PlusOutlined style={{ fontSize: 14 }} />
                  添加组合
                </Button>
              </Authorized>
            </Row>
            <StandardTable
              selectedRows={selectedRows}
              selectedRowKeys={selectedRowKeys}
              loading={loading}
              data={insDataSource}
              rowKey="insLsPkgId"
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </TabPane>
          <TabPane tab="公积金组合" key="2">
            <Row style={{ marginBottom: 16 }}>
              <Authorized authority="business:insLsPkg:insert" noMatch={null}>
                <Button type="primary" size="default" onClick={this.goFoundAdd}>
                  <PlusOutlined style={{ fontSize: 14 }} />
                  添加组合
                </Button>
              </Authorized>
            </Row>
            <StandardTable
              selectedRows={accuSelectedRows}
              selectedRowKeys={accuSelectedRowKeys}
              loading={loading}
              data={accuDataSource}
              rowKey="accuLsPkgId"
              columns={columns1}
              onSelectRow={this.handleAccuSelectRows}
              onChange={this.handleAccuStandardTableChange}
            />
          </TabPane>
        </Tabs>
      </div>
    );
  }
}

const CombinaFrom = Form.create()(Combina);
export default CombinaFrom;